<template>
  <el-card class="card" style="max-width: 75vw">
    <div class="card-header">
      <span class="title"> 我的作品 </span>
      <el-button id="sendNotice" type="primary" @click="createNew">创建新作品</el-button>
    </div>
    <div>
      <el-table class="listTable" :data="worksListData" :border=true style="width: 100%" :max-height="'70vh'">
        <el-table-column prop="title" label="作品标题" :width="tableWidth[0]" :align="'center'" />
        <el-table-column prop="createTime" label="发布时间" :width="tableWidth[1]" :align="'center'" />
        <el-table-column prop="clubName" label="所属社团" :width="tableWidth[2]" :align="'center'" />
        <el-table-column prop="options" label="操作" :width="tableWidth[3]" :align="'center'">
          <template #default="scope">
            <el-button id="buttonShow" @click="handleShowButton(scope.row)">查看</el-button>
            <el-button type="primary" id="buttonEdit" @click="handleEditButton(scope.row)">修改</el-button>
            <el-button type="danger" id="buttonDelete" @click="handleDeleteButton(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footerpager">
      <el-select v-model="pageSize" @change="onOptionChange" placeholder="Select" style="width: 120px">
        <el-option v-for="size in pageSizeOptions" :key="size.value" :label="size.label" :value="size.value" />
      </el-select>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :pager-count="7"
        @current-change="handleUpdateList" layout="prev, pager, next" :total="totalNum" />
      <div class="pageNow">
        当前
        <input class="pageInput" @blur="onChangePage" v-model="setCurrentPage" />
        页，共
        {{ totalPage }}
        页
      </div>
    </div>
  </el-card>

  <el-dialog class="workDialog" v-model="newWorkDialog" :title="dialogTitle" destroy-on-close :fullscreen="true" :before-close="handleCloseCreate" style="width: 80vw;">
    <el-form :model="newWorkForm" label-width="auto">
      <el-form-item label="作品标题">
        <el-input v-model="newWorkForm.title" style="width: 400px" />
      </el-form-item>
      <el-form-item label="发表社团">
        <el-select v-model="newWorkForm.clubId" placeholder="--请选择社团--" style="width: 220px">
          <el-option v-for="item in addedClubList" :key="item.clubId" :label="item.clubName" :value="item.clubId" />
        </el-select>
      </el-form-item>
      <el-form-item label="作品类型">
        <el-radio-group v-model="newWorkForm.type">
          <el-radio :value="0">文章</el-radio>
          <el-radio :value="1">视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="封面图片">
        <el-image style="width: 160px; height: 90px" :src="newWorkImgUrl" fit="cover" />
        <el-upload class="avatar-uploader" :beforeUpload="beforeImgUpload" :show-file-list="false"
          :accept="'image/jpeg,image/jpg,image/png,.jpg,.png,.jpeg'">
          <el-button id="uploadImgButton" type="primary">上传图片</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label-position="top" v-if="newWorkForm.type == 0" label="编辑文章">
        <text-editor :articleData="article"></text-editor>
      </el-form-item>
      <el-form-item v-if="newWorkForm.type == 1" label="上传视频">
        <el-upload class="upload-demo" drag :before-upload="beforeUploadVideo" accept="video/*" :limit="1">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽到此处 或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持视频文件
            </div>
            <div v-show="videoName != ''">已上传：{{ videoName }}</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="optionType" type="primary" @click="onSubmit">提交申请</el-button>
        <el-button v-else type="primary" @click="onModify">提交修改申请</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogVisible"
    title="提示"
    width="500"
  >
    <span>您确定要删除这个作品吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="deleteWork">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <show-works :id="workId" :flag="showFlag"></show-works>
</template>

<script setup>
import { onMounted, reactive, ref, watch ,onUnmounted} from 'vue';
import TextEditor from './TextEditor.vue';
import api from '@/api';
import showMessageTip from '@/utils/showMessage';
import { getAllText } from './TextEditor.vue';
import ShowWorks from './ShowWorks.vue';
import debounce from '@/utils/debounce';

const tableWidth=ref([]);
const pageSize = ref(10);
const tableWidthRatio=ref([0.35,0.2,0.2,0.25]);
const totalPage = ref(1); //总页数
const pageSizeOptions = ref([
  { value: 5, label: '5条/页' },
  { value: 10, label: '10条/页' },
  { value: 15, label: '15条/页' },
  { value: 20, label: '20条/页' },
]);
const totalNum = ref(0);
const currentPage = ref(1);
const setCurrentPage = ref(1);
const worksListData = ref([]);
const newWorkDialog = ref(false);
const newWorkForm = reactive({
  clubId: null,
  title: '',
  type: null,
});
const newWorkImgUrl = ref('');
const addedClubList = ref([]);
const imgData = ref(null);
const workData = ref('');
const optionType = ref(true);
const article = ref('');  //debug  '<p>11<span style="color: #e03e2d;"><strong>1231</strong></span>3</p>'
const tempFormData = reactive({});
const dialogTitle = ref('');
const workId = ref('');
const showFlag = ref(false);
const dialogVisible = ref(false);
var debounceSetColumnSize = null;
const videoName = ref('');

onMounted(async  () => {
  const width = document.querySelector('.card').getBoundingClientRect().width-40;
  tableWidth.value[3]=width;
  for(let i = 0; i<3 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[3] -= tableWidth.value[i];
  }
  await handleUpdateList();
  await getAddedClubList();
});
onMounted( () => {
  debounceSetColumnSize = debounce(setColumnSize, 300);
  window.addEventListener('resize', debounceSetColumnSize);
})
onUnmounted(() => {
  window.removeEventListener('resize', debounceSetColumnSize);
  debounceSetColumnSize.cancel();
});
const setColumnSize = () => {
  const width = document.querySelector('.card').getBoundingClientRect().width-40;
  tableWidth.value[3]=width;
  for(let i = 0; i<3 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[3] -= tableWidth.value[i];
  }
}

const onChangePage = async () => {
  if(Number(setCurrentPage.value) > totalPage.value){
    setCurrentPage.value = totalPage.value;
    currentPage.value = totalPage.value;
  }
  else if(setCurrentPage.value <= 0){
    setCurrentPage.value = 1;
    currentPage.value = 1;
  }
  else{
    currentPage.value = Number(setCurrentPage.value);
  }
  await handleUpdateList();
}

const onOptionChange = () => {
  setCurrentPage.value = 1;
  currentPage.value = 1;
}

watch(pageSize, async (newQuestion, oldQuestion) =>{
  await handleUpdateList();
})

const handleUpdateList = async () => {
  const reqData = reactive({
    pageSize: pageSize.value,
    page: currentPage.value,
  });
  const reqResult = await api.getSelfWorksList(reqData);
  if (reqResult[0] == 0) {
    const data = reqResult[1].data;
    if (data.code == 1) {
      worksListData.value = [];
      totalNum.value = data.data.total;
      worksListData.value = data.data.rows;
      totalPage.value = Math.ceil(totalNum.value / pageSize.value);
      setCurrentPage.value = currentPage.value;
    }
    else{
      showMessageTip('数据获取失败', 'error');
      return;
    }
  }
  else {
    showMessageTip('网络请求失败', 'error');
    return;
  }
}

const beforeImgUpload = async (file) => {
  if (!file.type.startsWith('image/')) {
    showMessageTip('不支持的文件格式', 'warning');
    return false;
  }
  else if (!(file.size / 1024 / 1024 < 2)) {
    showMessageTip('文件不能大于2M', 'warning')
    return false;
  }
  else {
    imgData.value = file;
    if (imgData.value != null) {
      newWorkImgUrl.value = await imgToUrl(imgData.value);
      showMessageTip('图片加载成功！', 'success');
    }
    return false;
  }
}
const handleCloseCreate = (done) => {
  ElMessageBox.confirm('内容未保存，确定要关闭吗?','提示',{
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      newWorkForm.title = '';
      imgData.value = null;
      newWorkImgUrl.value = null;
      workData.value = '';
      newWorkForm.clubId = null;
      newWorkForm.type = null;
      newWorkDialog.value = false;
      article.value = '';
      videoName.value = '';
      done();
    })
    .catch(() => {
    })
}
const getAddedClubList = async () => {
  const result = await api.getClubJoined();
  if (result[0] == 0) {
    const data = result[1].data;
    if (data.code == 1) {
      const dataList = data.data;
      for (let i = 0; i < dataList.length; i++) {
        const temp = {
          clubId: dataList[i].clubId,
          clubName: dataList[i].clubName,
        }
        addedClubList.value.push(temp);

      }
    }
    else{
    showMessageTip('社团信息获取失败', 'error');
    return;
    }
  }
  else {
    showMessageTip('网络请求失败', 'error');
    return;
  }
}
const imgToUrl = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
            resolve(event.target.result); // 返回Base64URL
        };
        reader.onerror = (error) => {
            reject(new Error('文件读取错误' + error));
        };
        reader.readAsDataURL(file);
    });
}

const onSubmit = async () => {
  const formData = new FormData();
  if(newWorkForm.title == '' || imgData.value == null || newWorkForm.clubId == null || newWorkForm.type == null){
    showMessageTip('请填写完整信息', 'warning');
    return;
  }
  if(newWorkForm.type == 0) {
    workData.value = getAllText();
    if(workData.value == '' || workData.value == null){
      showMessageTip('文章内容为空！', 'warning');
      return;
    }
    const blob = new Blob([workData.value], { type: 'text/html' });
    const file = new File([blob], 'work.html', { type: blob.type });
    formData.append('multimedia', file);
  }
  else if(newWorkForm.type == 1) {
    if(workData.value.type == '' || !workData.value.type.startsWith('video/')) {
      showMessageTip('请先上传视频！', 'warning');
      return;
    }
    formData.append('multimedia', workData.value);
  }
  formData.append('cover', imgData.value);
  formData.append('value1', newWorkForm.title);
  formData.append('value3', newWorkForm.type);
  formData.append('bigAffairType',2);
  formData.append('affairType',3);
  formData.append('clubId', newWorkForm.clubId);
  const reqResult = await api.uploadWorks(formData);
  if(reqResult[0] == 0) {
    const data = reqResult[1].data;
    if(data.code == 1) {
      showMessageTip('提交成功', 'success');
      newWorkForm.title = '';
      imgData.value = null;
      newWorkImgUrl.value = null;
      workData.value = '';
      newWorkForm.clubId = null;
      newWorkForm.type = null;
      newWorkDialog.value = false;
      article.value = '';
      videoName.value = '';
    }
    else{
      showMessageTip('提交失败', 'error');
      return;
    }
  }
  else{
    showMessageTip('网络请求失败', 'error');
    return;
  }
}
const onModify = async () => {
  const formData = new FormData();
  formData.append('value6', tempFormData.multiMediaId);
  if(newWorkForm.title == ''){
    showMessageTip('请填写完整信息', 'warning');
    return;
  }
  else if(tempFormData.title != newWorkForm.title){
    formData.append('value1', newWorkForm.title);
  }
  if(newWorkForm.clubId != tempFormData.clubId){
    formData.append('value4', newWorkForm.clubId);
  }
  if(imgData.value != null) {
    formData.append('cover', imgData.value);
  }
  if(newWorkForm.type == 0){
    if(newWorkForm.type == tempFormData.type){
      workData.value = getAllText();
    if(workData.value != tempFormData.article){
      const blob = new Blob([workData.value], { type: 'text/html' });
      const file = new File([blob], 'work.html', { type: blob.type });
      formData.append('value3', newWorkForm.type);
      formData.append('multimedia', file);
      }
    }
  }
  else if(newWorkForm.type == 1) {
    if(newWorkForm.type != tempFormData.type){
      if(workData.value.type != null && workData.value.type.startsWith('video/')) {
        formData.append('value3', newWorkForm.type);
        formData.append('multimedia', workData.value);
      }
      else{
        showMessageTip('请先上传视频！', 'warning');
        return;
      }
    }
    else{
      if(workData.value.type != null && workData.value.type.startsWith('video/')){
        formData.append('value3', newWorkForm.type);
        formData.append('multimedia', workData.value);
      }
    }
  }
  formData.append('bigAffairType',2);
  formData.append('affairType',4);
  const reqResult = await api.uploadWorks(formData);
  if(reqResult[0] == 0) {
    const data = reqResult[1].data;
    if(data.code == 1) {
      showMessageTip('提交成功', 'success');
      newWorkForm.title = '';
      imgData.value = null;
      newWorkImgUrl.value = null;
      workData.value = '';
      newWorkForm.clubId = null;
      newWorkForm.type = null;
      newWorkDialog.value = false;
      article.value = '';
    }
    else{
      showMessageTip('提交失败', 'error');
      return;
    }
  }
  else{
    showMessageTip('网络请求失败', 'error');
    return;
  }
}
const createNew = () => {
  dialogTitle.value = '创建';
  optionType.value = true;
  newWorkDialog.value = true;
}
const handleEditButton = async (rowData) => {
  dialogTitle.value = '修改';
  optionType.value = false;
  newWorkDialog.value = true;
  const reqResult = await api.getWorksInfo({ multiMediaId: rowData.multiMediaId });
  if(reqResult[0] == 0) {
    const data = reqResult[1].data;
    if(data.code == 1) {
      newWorkForm.title = data.data.title;
      const temp = addedClubList.value.find(item => item.clubName == data.data.clubName);
      newWorkForm.clubId = temp.clubId;
      newWorkForm.type = data.data.type;
      newWorkImgUrl.value = data.data.coverUrl;
      tempFormData.clubId = newWorkForm.clubId;
      tempFormData.title = newWorkForm.title;
      tempFormData.type = newWorkForm.type;
      tempFormData.multiMediaId = rowData.multiMediaId
      if(data.data.multiMediaUrl == '' || data.data.multiMediaUrl == null){
        showMessageTip('文章获取失败！', 'warning');
        return;
      }
      if(tempFormData.type == 0){
        await getArticle(data.data.multiMediaUrl);
        tempFormData.article = article.value;
      }
    }
    else{
      showMessageTip('数据获取失败', 'error');
      newWorkDialog.value = true;
      return;
    }
  }
  else{
    showMessageTip('网络请求失败', 'error');
    newWorkDialog.value = true;
    return;
  }
}
const handleShowButton = (rowData) => {
  workId.value = rowData.multiMediaId;
  showFlag.value = !showFlag.value;
}
const getArticle = async (url) => {
  const result = await api.getArticle(url);
  if(result[0] == 0) {
    article.value = result[1].data;
  }
  else{
    showMessageTip('文章内容获取失败', 'error');
    return;
  }
}
const handleDeleteButton=async(rowData)=>{//删除
 dialogVisible.value=true;
  workId.value=rowData.multiMediaId
}
const deleteWork =async()=>{
  const Id = ref({
    multiMediaId:workId.value
  })
  const result = await api.deleteArticle(Id.value);
  if (result[0] == 0) {
    const data = result[1].data;
    if (data.code == 1) {
      showMessageTip('已经删除该作品', 'success');
      return
    }
    else {
      showMessageTip('操作失败', 'error');
      return;
    }
 }
 else{
  showMessageTip('网络请求失败','error');
 }
}
const beforeUploadVideo = async (file) => {
  if(!file.type.startsWith('video/')){
    showMessageTip('不支持的文件格式', 'warning');
    return false;
  }
  else if(!(file.size / 1024 / 1024 < 200)){
    showMessageTip('视频大小不能超过200MB', 'warning');
    return false;
  }
  else{
    workData.value = file;
    if(workData.value != '' ) {
      videoName.value = workData.value.name;
      showMessageTip('视频加载成功', 'success');
    }
    else{
      showMessageTip('视频加载失败', 'warning');
    }
    return false;
  }
}
</script>

<style scoped>
.listTable{
  margin-top: 14px;
}
:deep(.listTable .el-table__header-wrapper th){
  background-color: #549DFD;
  color: #fff;
  font-family: 'Microsoft YaHei';
}   
.footerpager{
  margin-top: 20px;
  padding-left: 5px;
  display: flex;
}
.pageNow{
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14.5px;
}
.pageInput{
  margin-left: 5px;
  margin-right: 5px;
  width: 25px;
  text-align: center;
} 
.card-header{
  display: flex;
  padding-left: 10px;
}
#sendNotice{
  margin-left: auto;
  margin-right: 10px;
  background-color: #00a31b;
  border: none;
}
#sendNotice:hover{
  background-color: #1ac437;
}
.title {
  margin-left: 5px;
  font-weight: bold;
  font-size: 30px;
  font-family: "黑体";
}
#uploadImgButton{
  margin-left:15px;
}
</style>